package com.cos.shop.dao.impl;

import com.cos.shop.dao.AddressDao;
import com.cos.shop.entity.Address;
import com.cos.shop.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author: COS
 * @time: 2023/5/11 15:25
 * @description:
 */
public class AddressDaoImpl implements AddressDao {

    private QueryRunner qr = new QueryRunner(DBUtils.getDataSource());

    @Override
    public int setUserAddressNotDefault(int uid) throws SQLException {
        String sql = "update address set a_state =0 where u_id = ?";
        return qr.update(sql,uid);
    }

    @Override
    public int setUserAddressDefault(int aid) throws SQLException {
        String sql = "update address set a_state =1 where a_id = ?";
        return qr.update(sql,aid);
    }

    @Override
    public int insertAddress(Address a) throws SQLException {
        String sql = "insert into address values (default,?,?,?,?,?)";
        return qr.update(sql,
                a.getUid(),
                a.getAname(),
                a.getAphone(),
                a.getAdetail(),
                a.getAstate());
    }

    @Override
    public int updateAddress(Address a) throws SQLException {
        String sql = "update address set a_name = ?,a_phone = ?,a_detail =? where a_id=?";
        return qr.update(sql,
                a.getAname(),
                a.getAphone(),
                a.getAdetail(),
                a.getAid());
    }

    @Override
    public int delete(int id) throws SQLException {
        return qr.update("delete from address where a_id = ?", id);
    }

    @Override
    public List<Address> getAll(int uid) throws SQLException {
        String sql = "select " +
                "  `a_id` 'aid'," +
                "  `u_id` 'uid'," +
                "  `a_name` 'aname'," +
                "  `a_phone` 'aphone'," +
                "  `a_detail` 'adetail'," +
                "  `a_state` 'astate' " +
                " from address where u_id = ? order by a_state desc";
        return qr.query(sql, new BeanListHandler<>(Address.class), uid);
    }
}
